package org.testis.gui.mvc.view.testdesign;

import org.testis.gui.mvc.view.*;
import org.testis.gui.mvc.utilities.Validatable;
import org.testis.gui.mvc.controller.testdesign.TestCaseGroupController;
import org.testis.gui.mvc.controller.TestDesignControllerList;
import org.testis.gui.mvc.controller.testdesign.ConditionsController;
import org.testis.gui.mvc.utilities.ValidationUtils;
import org.testis.gui.mvc.view.labels.LabelPairSettingsView;
import java.awt.Frame;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import org.orm.PersistentException;

/**
 *
 * @author  Cahit Emir Erel
 */
public class TestCaseGroupView extends AtofBaseDialog implements
        AbstractViewPanel, Validatable {

    private static final long serialVersionUID = 21612374L;
    private boolean m_editMode;
    private String m_windowTitle;
    private LabelPairSettingsView m_labelSettingsView;

    /** Creates new form AddTestPlanView */
    public TestCaseGroupView(Frame parent,
            boolean modal,
            boolean editMode) {
        super(parent,
                modal);
        m_editMode = editMode;
        if (editMode) {
            m_windowTitle = "Edit Test Case Group";
        } else {
            m_windowTitle = "Add Test Case Group";
        }
        m_labelSettingsView = new LabelPairSettingsView();
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        runAlwaysChoice = new java.awt.Choice();
        nameTextField = new javax.swing.JTextField();
        descriptionTextField = new javax.swing.JTextField();
        timeoutTextField = new javax.swing.JTextField();
        nameLabel = new javax.swing.JLabel();
        descriptionLabel = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        timeoutLabel = new javax.swing.JLabel();
        runAlwaysLabel = new javax.swing.JLabel();
        labelSettingsScrollPane = new javax.swing.JScrollPane();
        labelSettingsScrollPane.setViewportView(m_labelSettingsView);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(m_windowTitle);
        setMinimumSize(new java.awt.Dimension(360, 350));
        setModal(true);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        String label;
        if (m_editMode) {
            label = "Save Changes";
        } else {
            label = "Add Test Case Group";
        }
        saveButton.setText("Save");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        runAlwaysChoice.add("true");
        runAlwaysChoice.add("false");
        runAlwaysChoice.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                runAlwaysChoiceItemStateChanged(evt);
            }
        });

        nameTextField.setFont(new java.awt.Font("Dialog", 0, 11));
        nameTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameTextFieldActionPerformed(evt);
            }
        });
        nameTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                nameTextFieldFocusLost(evt);
            }
        });

        descriptionTextField.setFont(new java.awt.Font("Dialog", 0, 11));
        descriptionTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                descriptionTextFieldActionPerformed(evt);
            }
        });
        descriptionTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                descriptionTextFieldFocusLost(evt);
            }
        });

        timeoutTextField.setEditable(false);
        timeoutTextField.setFont(new java.awt.Font("Dialog", 0, 11));

        nameLabel.setFont(new java.awt.Font("Dialog", 0, 11));
        nameLabel.setText("* Name:");

        descriptionLabel.setFont(new java.awt.Font("Dialog", 0, 11));
        descriptionLabel.setText("Description:");

        timeoutLabel.setFont(new java.awt.Font("Dialog", 0, 11));
        timeoutLabel.setText("Timeout:");

        runAlwaysLabel.setFont(new java.awt.Font("Dialog", 0, 11));
        runAlwaysLabel.setText("* Run Always:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(106, 106, 106)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(runAlwaysLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(timeoutLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(descriptionLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 86, Short.MAX_VALUE)
                            .addComponent(nameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(nameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)
                            .addComponent(descriptionTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)
                            .addComponent(runAlwaysChoice, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(timeoutTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE))))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {descriptionLabel, nameLabel});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nameLabel)
                    .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(descriptionLabel)
                    .addComponent(descriptionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(19, 19, 19)
                        .addComponent(runAlwaysChoice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(runAlwaysLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(timeoutLabel)
                    .addComponent(timeoutTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(73, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("General", jPanel1);
        jTabbedPane1.addTab("Labels", labelSettingsScrollPane);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, saveButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(saveButton))
                .addContainerGap())
        );

        ConditionsController.createInstance(m_editMode).initialize();
        jTabbedPane1.addTab("Conditions", ConditionsController.getInstance().getConditionView());

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void nameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameTextFieldActionPerformed
        try {
            TestDesignControllerList.newInstance().getTestCaseGroupController().
                    operationChangeName(nameTextField.getText());
        } catch (Exception e) {
            //  Handle exception
        }
    }//GEN-LAST:event_nameTextFieldActionPerformed

    private void nameTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_nameTextFieldFocusLost
        try {
            TestDesignControllerList.newInstance().getTestCaseGroupController().
                    operationChangeName(nameTextField.getText());
        } catch (Exception e) {
            //  Handle exception
        }
    }//GEN-LAST:event_nameTextFieldFocusLost

    private void descriptionTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_descriptionTextFieldActionPerformed
        try {
            TestDesignControllerList.newInstance().getTestCaseGroupController().
                    operationChangeDescription(descriptionTextField.getText());
        } catch (Exception e) {
            //  Handle exception
        }
}//GEN-LAST:event_descriptionTextFieldActionPerformed

    private void descriptionTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_descriptionTextFieldFocusLost
        try {
            TestDesignControllerList.newInstance().getTestCaseGroupController().
                    operationChangeDescription(descriptionTextField.getText());
        } catch (Exception e) {
            //  Handle exception
        }
}//GEN-LAST:event_descriptionTextFieldFocusLost

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed

        WindowListener[] listeners = getWindowListeners();
        for (int i = 0; i < listeners.length; i++) {
            this.removeWindowListener(listeners[i]);
        }
        this.setEnabled(false);
        this.dispose();
        this.invalidate();
        TestDesignControllerList.newInstance().getTestCaseGroupController().
                operationCloseWindow();
        ConditionsController.createInstance(m_editMode).operationClose();
    }//GEN-LAST:event_formWindowClosed

    private void runAlwaysChoiceItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_runAlwaysChoiceItemStateChanged

        TestDesignControllerList.newInstance().getTestCaseGroupController().
                operationChangeRunAlways(runAlwaysChoice.getSelectedItem());
    }//GEN-LAST:event_runAlwaysChoiceItemStateChanged

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        if (!validateForm()) {
            return;
        }
        saveButton.setEnabled(false);

        LinkedList<String> labels = m_labelSettingsView.getSelectedLabelNames();
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("name", nameTextField.getText());
        params.put("description", descriptionTextField.getText());
        params.put("runAlways", runAlwaysChoice.getSelectedItem());
        params.put("labels", labels);

        LinkedHashMap<Integer, String> listOfCond = ConditionsController.getInstance().getConditionsList();

        if (listOfCond != null) {
            params.put("conditions", listOfCond);
        }

        if (m_editMode) {
            TestDesignControllerList.newInstance().getTestCaseGroupController().
                    operationSaveTestCaseGroup(params);
        } else {
            try {
                TestDesignControllerList.newInstance().getTestCaseGroupController().
                        operationAddTestCaseGroup(nameTextField.getText(),
                        descriptionTextField.getText(),
                        runAlwaysChoice.getSelectedItem(),
                        labels);
            } catch (PersistentException ex) {
                ex.printStackTrace();
            }
        }
        dispose();
    }//GEN-LAST:event_saveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed
    @Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals(
                TestCaseGroupController.SHOW_ADD_TEST_CASE_GROUP)) {
            this.centerParent();
        }
        if (evt.getPropertyName().equals(TestCaseGroupController.CHANGE_NAME)) {
            nameTextField.setText(evt.getNewValue().toString());
        } else if (evt.getPropertyName().equals(
                TestCaseGroupController.CHANGE_DESCRIPTION)) {
            descriptionTextField.setText(evt.getNewValue().toString());
        } else if (evt.getPropertyName().equals(
                TestCaseGroupController.CHANGE_RUN_ALWAYS)) {
            runAlwaysChoice.select(evt.getNewValue().toString());
        } else if (evt.getPropertyName().equals(
                TestCaseGroupController.CHANGE_TIMEOUT)) {
            timeoutTextField.setText(evt.getNewValue().toString());
        }
    }

    @Override
    public boolean validateForm() {
        boolean valid = true;
        StringBuilder builder = new StringBuilder();
        if (ValidationUtils.isEmpty(nameTextField.getText())) {
            builder.append("Name must not be empty.\n");
            valid = false;
        }
        if (!valid) {
            JOptionPane.showMessageDialog(null,
                    builder.toString(),
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        return valid;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel descriptionLabel;
    private javax.swing.JTextField descriptionTextField;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JScrollPane labelSettingsScrollPane;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JTextField nameTextField;
    private java.awt.Choice runAlwaysChoice;
    private javax.swing.JLabel runAlwaysLabel;
    private javax.swing.JButton saveButton;
    private javax.swing.JLabel timeoutLabel;
    private javax.swing.JTextField timeoutTextField;
    // End of variables declaration//GEN-END:variables
}
